package cc.atliberty.dom4j;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class DOM4J {
    public static void main(String[] args) throws DocumentException, IOException {
        
        // 读取XML文件
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(DOM4J.class.getClassLoader().getResource("book.xml"));
            Element rootElement = document.getRootElement();
            System.out.println("book.xml文件的根节点的名字是：" + rootElement.getName());
            List<Element> booksSubElementList = rootElement.elements();
            for (Element bookElement : booksSubElementList) {
                System.out.println("书架的子标签的名字是：" + bookElement.getName());
                List<Element> bookSubElementList = bookElement.elements();
                for (Element bookSubElement : bookSubElementList) {
                    System.out.println(bookSubElement.getName() + " : " + bookSubElement.getText());
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        
        //写入XML文件
        Document document = saxReader.read(DOM4J.class.getClassLoader().getResource("book.xml"));
        Element root = document.getRootElement();
        Element book = root.addElement("书");
        book.addElement("书名").addText("ASP.NET");
        book.addElement("作者").addText("老陈");
        book.addElement("售价").addText("123");
        
        XMLWriter writer = new XMLWriter(new FileWriter("E:\\javaweb\\workspace_idea1\\javaweb-exam\\src\\main\\resources\\book.xml"));
        writer.write(document);
        writer.close();

        OutputFormat prettyPrint = OutputFormat.createPrettyPrint();
        prettyPrint.setEncoding("UTF-8");
        new XMLWriter(new FileWriter("book.xml"), prettyPrint);
    }
}
